package cmd

import (
	"context"
	"github.com/gogf/gf/v2/net/goai"
	"meta-self/internal/consts"
	"meta-self/internal/model"
	"meta-self/internal/router"
	"meta-self/internal/service"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			// 注册全局中间件
			s.BindMiddleware("/*any", []ghttp.HandlerFunc{
				service.Middleware().Ctx,             // 初始化请求上下文，一般需要第一个进行加载，后续中间件存在依赖关系
				service.Middleware().CORS,            // 跨域中间件，自动处理跨域问题
				service.Middleware().ResponseHandler, // HTTP响应预处理，在业务处理完成后，对响应结果进行格式化和错误过滤，将处理后的数据发送给请求方
			}...)
			s.Group("/v1", func(group *ghttp.RouterGroup) {
				// 注册客户端路由
				router.Client(ctx, group)
				router.Api(ctx, group)
			})
			enhanceOpenAPIDoc(s)
			s.Run()
			return nil
		},
	}
)

func enhanceOpenAPIDoc(s *ghttp.Server) {

	openapi := s.GetOpenApi()
	openapi.Config.CommonResponse = model.Response{}
	openapi.Config.CommonResponseDataField = `Data`
	openapi.Components = goai.Components{
		SecuritySchemes: goai.SecuritySchemes{
			"apiKey": goai.SecuritySchemeRef{
				Ref: "",
				Value: &goai.SecurityScheme{
					// 此处type是openApi的规定，详见 https://swagger.io/docs/specification/authentication/api-keys/
					Type: "apiKey",
					In:   "header",
					Name: "Authorization",
				},
			},
		},
	}
	// API description.
	openapi.Info = goai.Info{
		Title:       consts.OpenAPITitle,
		Description: consts.OpenAPIDescription,
		Contact: &goai.Contact{
			Name: consts.OpenAPIContactName,
			URL:  consts.OpenAPIContactUrl,
		},
	}
	openapi.Security = &goai.SecurityRequirements{goai.SecurityRequirement{"apiKey": []string{}}}
}
